// import 'package:ad_suyi_flutter_sdk/ad_suyi_ad.dart';
// import 'package:flutter/material.dart';
//

import 'package:ad_suyi_flutter_sdk/ad_suyi_ad.dart';
import 'package:ad_suyi_flutter_sdk/ad_suyi_base.dart';
import 'package:flutter/material.dart';

import 'key.dart';

class NativePage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => NativeState();
}

class NativeState extends State<NativePage> {
  ADSuyiFlutterNativeAd? _nativeAd;

  List<dynamic> _items = List.generate(10, (i) => i);
  ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        _getAdData();
      }
    });
  }

  _getAdData() async {
    _nativeAd!.load();
  }

  void createNativeAd(BuildContext context) {
    if (_nativeAd == null) {
      MediaQueryData queryData = MediaQuery.of(context);
      var width = queryData.size.width;
      /**
       * 由于flutter对接安卓原生广告无法提前获取到部分渠道广告视图的高度，开发者需要做一下处理。
       * 例如每个渠道都申请大小相近的广告样式，可在此设置固定比例。（优量汇：选横版纯图片；穿山甲：文字浮层；百度：三图；快手：横版大图）
       * 由于demo上用的广告位素材样式不固定，我们直接写16：12进行测试。
       * 设置比例的作用，主要是防止广告素材被遮挡，导致收益降低和合规问题。
       */
      var height = width / 16 * 12;
      _nativeAd = ADSuyiFlutterNativeAd(
          posId: KeyManager.nativePosid(), width: width, height: height);

      _nativeAd!.onFailed = (AdErrorInfo adErrorInfo) {
        print("信息流广告加载失败 errorCode : " +
            adErrorInfo.errorCode.toString() +
            " errorDescription : " +
            adErrorInfo.errorDescription);
      };

      _nativeAd!.onReceived = (ADSuyiFlutterNativeAdView adView) {
        setState(() {
          var adWidget = ADSuyiWidget(adView: adView);
          // 关闭回调
          adView.onClosed = (AdInfo adInfo) {
            print("信息流广告关闭了 platformName : " +
                adInfo.platformName +
                " ecpmPrecision : " +
                adInfo.ecpmPrecision +
                " ecpm : " +
                adInfo.ecpm.toString());
            setState(() {
              _items.remove(adWidget);
              adView.release();
            });
          };
          // 曝光回调
          adView.onExposed = (AdInfo adInfo) {
            print("信息流广告曝光了 platformName : " +
                adInfo.platformName +
                " ecpmPrecision : " +
                adInfo.ecpmPrecision +
                " ecpm : " +
                adInfo.ecpm.toString());
          };

          _items.add(adWidget);
          _items.addAll(List.generate(1, (i) => i));
        });
      };

    }
  }

  @override
  Widget build(BuildContext context) {
    createNativeAd(context);
    return Scaffold(
      appBar: AppBar(
        title: Text("Native"),
      ),
      body: Center(
        child: ListView.builder(
            itemCount: _items.length,
            controller: _scrollController,
            itemBuilder: (BuildContext context, int index) {
              final item = _items[index];
              if (item is Widget) {
                return item;
              } else {
                return Container(
                    width: 300,
                    height: 150,
                    child: Text("Cell_dart", style: TextStyle(fontSize: 40)));
              }
            }),
      ),
    );
  }

  @override
  void dispose() {
    for (var item in _items) {
      if (item is ADSuyiFlutterNativeAdView) {
        item.release();
      }
    }
    _nativeAd!.release();
    _nativeAd = null;
    super.dispose();
  }
}
